package com.aube.interact.fighter.control;

import android.content.Context;
import android.util.Log;
import android.view.ViewGroup;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.interact.fighter.GoodsHotpotLayout;
import com.aube.interact.fighter.GoodsStoreLayout;
import com.aube.interact.fighter.IGoodsFavorListener;
import com.aube.interact.fighter.model.AddFavorResult;
import com.huyn.baseframework.dynamicload.video.AbstractController;
import com.huyn.baseframework.dynamicload.video.model.GoodsFavorListModel;
import com.huyn.baseframework.dynamicload.video.model.GoodsItem;
import com.huyn.baseframework.dynamicload.video.model.GoodsListModel;
import com.huyn.baseframework.dynamicload.video.model.GoodsModel;
import com.huyn.baseframework.dynamicload.video.model.GoodsPoint;
import com.huyn.baseframework.dynamicload.video.model.GoodsRoute;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.net.BFJSONRequest;
import com.huyn.baseframework.net.HttpRequestLoader;
import com.huyn.baseframework.net.OpenApi;
import com.huyn.baseframework.utils.UmengUtils;
import com.huyn.baseframework.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;

/**
 * Created by hill on 10/24.
 */
public class GoodsCardController extends AbstractController<GoodsModel> implements IGoodsFavorListener {

    private GoodsListModel mGoodsData;
    private GoodsStoreLayout.IDataInflater mIDataInflater;

    public GoodsCardController(Context context, ViewGroup mRoot) {
        super(context, mRoot);

        ((GoodsHotpotLayout) mCardRoot).bindVideo(mChannel);
    }

    public GoodsCardController(Context context, ViewGroup mRoot, GoodsStoreLayout.IDataInflater dataInflater) {
        super(context, mRoot);
        mIDataInflater = dataInflater;

        ((GoodsHotpotLayout) mCardRoot).bindVideo(mChannel);
    }

    public GoodsCardController(Context context, ViewGroup mRoot, ChannelDetail mChannel, IControllerCallback callback) {
        super(context, mRoot, mChannel, callback);

        ((GoodsHotpotLayout) mCardRoot).bindVideo(mChannel);
    }

    @Override
    public boolean setupCards(long selectedIndex, boolean freshData, boolean autoBegin) {
        Log.e(TAG, "setupCards 3 arg");
//        mCurrentData = null;
        if(setupCards(selectedIndex, autoBegin))
            return true;

        if(freshData) {
            loadGoodsTimeLine(selectedIndex);
            return true;
        }

        return false;
    }

    public boolean setupCards(long selectedIndex, boolean autoBegin) {
        Log.e(TAG, "seetupCards 2 arg");
        clearCardsList();
        if(mGoodsData == null || mGoodsData.data == null)
            return false;
        synchronized (mCardsList) {
            mCardsList.clear();
            long currentSecond = selectedIndex / 1000;
            for(GoodsModel item : mGoodsData.data) {
                if(item.endSeconds <= currentSecond)
                    continue;
                mCardsList.add(item);
            }

            if(!autoBegin)
                locateCardByTime(selectedIndex);
        }
        return true;
    }

    public List<GoodsModel> getGoodsStoreData() {
        return mGoodsData.data;
    }

    private long currentSecond=0;
    @Override
    public boolean locateCardByTime(long current) {
        if(current < 0)
            return manageCard(null);

        synchronized (mCardsList) {
            currentSecond = current / 1000;

            if(mCurrentData != null) {
                if(mCurrentData.endSeconds <= currentSecond || mCurrentData.startSeconds > currentSecond)
                    mCurrentData = null;
                else
                    return manageCard(mCurrentData, currentSecond);
            }

            if(mCardsList.size() == 0)
                return manageCard(null);

            GoodsModel firstItem = mCardsList.get(0);
            if(firstItem.startSeconds <= currentSecond && firstItem.endSeconds > currentSecond) {
                Utils.Log(TAG, "GOODS____load card at time:" + currentSecond);
                mCardsList.remove(0);
                return manageCard(firstItem, currentSecond);
            } else if(firstItem.endSeconds <= currentSecond) {
                mCardsList.remove(0);
            }

            return manageCard(null);
        }
    }

    @Override
    public boolean manageCard(GoodsModel data) {
        return manageCard(data, 0);
    }

    public boolean manageCard(GoodsModel data, long current) {
        if(data != null) {
            if(mCurrentData != null)  {
                if(mCurrentData.rid.equalsIgnoreCase(data.rid)) {
//                    Utils.Log(TAG, "GOODS____update");
                } else {
                    mCurrentData = data;
                    appendToScreen(data, current);
                }
            } else {
                mCurrentData = data;
                appendToScreen(data, current);
            }
        } else {
            mCurrentData = null;
            if(mCardRoot.getChildCount() != 0) {
                removeFromScreen();
            }
        }
        return true;
    }

    public void removeFromScreen() {
        if(mCardRoot != null)
            ((GoodsHotpotLayout) mCardRoot).onDestroy();
    }

    @Override
    public void appendToScreen(final GoodsModel data) {
        appendToScreen(data, 0);
    }

    protected void appendToScreen(final GoodsModel data, final long current) {
        removeFromScreen();
        try {
//            GoodsRoute route = setupRoutesStack(current);
            setupPosStack(current);
//            ((GoodsHotpotLayout) mCardRoot).showHotpot(data, route, this);
            if(data.goodsVo != null)
                ((GoodsHotpotLayout) mCardRoot).showHotpot(data, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Stack<GoodsRoute> mListPosStack = null;

    private void setupPosStack(long current) {
        mListPosStack = new Stack<>();
        synchronized(mListPosStack) {
            if (mCurrentData == null && mCurrentData.timelineCircleRespVoList == null)
                return;

            for(int i = mCurrentData.timelineCircleRespVoList.size() - 1; i >= 0; i--) {
                GoodsPoint goodsPoint = mCurrentData.timelineCircleRespVoList.get(i);
                if(goodsPoint == null && goodsPoint.circleTrajectoryList == null)
                    continue;

                for(int j = goodsPoint.circleTrajectoryList.size() - 1; j >= 0; j--) {
                    GoodsRoute item = goodsPoint.circleTrajectoryList.get(i);
                    if (item.s >= current)
                        mListPosStack.push(item);
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void loadGoodsTimeLine(final long selectedIndex) {
        Log.e(TAG, "loadGoodsTimeLine");
        if(mChannel == null) {
            Utils.showToast(context, "没有节目");
            Log.e(TAG, "loadGoodsTimeLine: mChannel = null");
            return;
        }
        HashMap<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put(OpenApi.API_METHOD, OpenApi.GOODS_TIMELINE);
        parameterMap.put("showid", mChannel.showid);
        parameterMap.put("videoid", mChannel.videoid);
        BFJSONRequest request = new BFJSONRequest(GoodsListModel.class, parameterMap, new Response.Listener<GoodsListModel>() {

            @Override
            public void onResponse(GoodsListModel response) {
                if(response.success()) {
                    mGoodsData = response;
                    mIDataInflater.fillData(mGoodsData.data);
                    setupCards(selectedIndex, true);
                } else {
//                    Utils.showToast(context, response.errormsg);
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "onErrorResponse: error = " + error.getMessage());
            }

            @Override
            public void onStart() {
                Log.e(TAG, "onStart");
            }
        });
        request.setTag(TAG);
        HttpRequestLoader.getInstance(context).startCacheLoader("", request, true);

        loadFavorGoods();
    }

    public void operateFavor(String goodsId, boolean yes) {
        if(mChannel == null) {
            Utils.showToast(context, "没有节目");
            return;
        }
        HashMap<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put(OpenApi.API_METHOD, OpenApi.ADD_FAVOR);
        parameterMap.put("showid", mChannel.showid);
        parameterMap.put("videoid", mChannel.videoid);
        parameterMap.put("goodsid", goodsId);
        parameterMap.put("state", yes?"1":"0");
        BFJSONRequest request = new BFJSONRequest(AddFavorResult.class, parameterMap, new Response.Listener<AddFavorResult>() {

            @Override
            public void onResponse(AddFavorResult response) {
                if(response.success()) {
//                    Utils.showToast(context, response.data);
//                    loadFavorGoods();
                } else {
//                    Utils.showToast(context, response.errormsg);
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
            }

            @Override
            public void onStart() {
            }
        });
        request.setTag(TAG);
        HttpRequestLoader.getInstance(context).startCacheLoader("", request, true);
    }

    public void loadFavorGoods() {
        if(mChannel == null) {
            Utils.showToast(context, "没有节目");
            return;
        }
        HashMap<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put(OpenApi.API_METHOD, OpenApi.FAVOR_LIST);
        parameterMap.put("showid", mChannel.showid);
        parameterMap.put("videoid", mChannel.videoid);
        BFJSONRequest request = new BFJSONRequest(GoodsFavorListModel.class, parameterMap, new Response.Listener<GoodsFavorListModel>() {

            @Override
            public void onResponse(GoodsFavorListModel response) {
                if(response.success()) {
                    if(response.getSize() == 0)
                        return;
                    DataManager.getInstance(context).update(response.getGoodsList());
                } else {
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
            }

            @Override
            public void onStart() {
            }
        });
        request.setTag(TAG);
        HttpRequestLoader.getInstance(context).startCacheLoader("", request, true);
    }

    /**
     * Implementation of GoodsHotpotLayout.IAddFavorListener
     */
    @Override
    public void doFavorEvent(GoodsItem item) {
        //add goodsitem
        operateFavor(item._id, true);

        List<GoodsItem> list = new ArrayList<>();
        list.add(item);
        if (iControllerCallback != null)
            iControllerCallback.onGoodsAdd(list);


        if(mChannel != null)
            UmengUtils.reportUmengEvent(context, UmengUtils.ADD_TO_CART, UmengUtils.appendLabels(mChannel.videoTitle, mChannel.videoid, item.tlTitle, item._id));
    }

    @Override
    public void manageTool() {
        if (iControllerCallback != null)
            iControllerCallback.managerTools();
    }

    @Override
    public void cancelFavor(String id) {
        operateFavor(id, false);

        if (iControllerCallback != null)
            iControllerCallback.cancelGoods(id);
    }

    @Override
    public int[] getCartLocation() {
        if (iControllerCallback != null)
            return iControllerCallback.getCartLocation();
        return null;
    }

    @Override
    public float[] getCardPosition() {
        if(mListPosStack == null)
            return null;
        synchronized (mListPosStack) {
            if(mListPosStack.size() == 0)
                return null;

            GoodsRoute route;
            while (true) {
                route = mListPosStack.pop();
                if (route == null)
                    return null;

                GoodsRoute item = mListPosStack.peek();
                if(item == null) {
                    mListPosStack.push(route);
                    return route.get();
                }

                if(currentSecond <= route.s) {
                    mListPosStack.push(route);
                    return route.get();
                } else if(currentSecond <= item.s) {
                    mListPosStack.push(route);
                    return route.get();
                } else {
                    //continue
                }
            }
        }
    }

    @Override
    public int getProgress() {
        if (iControllerCallback != null)
            return (int) iControllerCallback.getCurrentProgress();
        return 0;
    }

    @Override
    public void hideFavorCart() {
        if(iControllerCallback != null)
            iControllerCallback.hideFavorCart();
    }

}
